<?php 

namespace PAT\ProductBundle\Controller;

use Symfony\Component\HttpFoundation\Response;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use PAT\ProductBundle\Entity\Product;
use PAT\ProductBundle\Form\CategoryRechercheForm;
use PAT\ProductBundle\Form\StockType;
use PAT\ProductBundle\Form\PictureType;
use PAT\ProductBundle\Entity\CategoryRepository;
use PAT\CommentBundle\Entity\Comment;
use \DateTime;

class ProductController extends Controller
{    
    public function indexAction()
    {	
        $repository = $this->getDoctrine()->getEntityManager()->getRepository('PATProductBundle:Product');

        $product_list = $repository->findAll();

        $form = $this->container->get('form.factory')->create(new CategoryRechercheForm());

        return $this->container->get('templating')->renderResponse('PATProductBundle:Default:index.html.twig', array(
                        'product_list' => $product_list,
                        'form' => $form->createView()
        ));
    }

    public function createAddForm($comment) {
        
        return $this->createFormBuilder($comment)
                        ->add('title', 'text')
                        ->add('text', 'textarea')
                        ->add('rate', 'choice', array(
                            'choices' => array(
                                '0' => '0',
                                '0.5' => '0.5',
                                '1' => '1',
                                '1.5' => '1.5',
                                '2' => '2',
                                '2.5' => '2.5',
                                '3' => '3',
                                '3.5' => '3.5',
                                '4' => '4',
                                '4.5' => '4.5',
                                '5' => '5'
                            )
                        ))
                        ->getForm();
    }
    
    public function displayAction($id)
    {
        $user = $this->container->get("security.context")->getToken()->getUser();
        $repository = $this->getDoctrine()->getEntityManager()->getRepository('PATProductBundle:Product');
        $product = $repository->find($id);

        if($product === null)
        {
                throw $this->createNotFoundException('Produit [id='.$id.'] inexistant !');
        }
        
        $comment = new Comment();
        
        $addForm = $this->createAddForm($comment);
        
        $request = $this->get('request');

        if ($request->getMethod() == 'POST')
        {
            $addForm->bindRequest($request);
            if ($addForm->isValid()) 
            {
                $comment->setUser($user);
                $comment->setPubDate(new DateTime());
                $comment->setProduct($product);
                $em = $this->getDoctrine()->getEntityManager();
                $em->persist($comment);
                $em->flush();

                return $this->redirect($this->generateUrl("pat_product_display", array('id' => $id)));
            }
        }

        return $this->render('PATProductBundle:Default:display.html.twig', array(
            'addForm' => $addForm->createView(),
            'product' => $product,
            'user' => $user
        ));
    }

    public function catalogAction()
    {
        $category_list = $this->getDoctrine()
                                        ->getEntityManager()
                                        ->getRepository('PATProductBundle:Category')
                                        ->selectChildCategory();

        return $this->render('PATProductBundle:Default:catalog.html.twig', array(
                        'category_list' => $category_list
        ));
    }
    
    public function catalogByCatergoryAction($id)
    {		
        $product_list = $this->getDoctrine()
                                        ->getEntityManager()
                                        ->getRepository('PATProductBundle:Category')
                                        ->selectCategoryFilles($id);

        return $this->render('PATProductBundle:Default:category.html.twig', array(
                        'product_list' => $product_list
        ));
    }

    public function productByCategoryAction($id)
    {		
        $product_list = $this->getDoctrine()
                                        ->getEntityManager()
                                        ->getRepository('PATProductBundle:Product')
                                        ->selectProductByCategory($id);

        return $this->render('PATProductBundle:Default:product.html.twig', array(
                        'product_list' => $product_list
        ));
    }

    public function rechercherAction()
    {
        $request = $this->container->get('request');

        if($request->isXmlHttpRequest())
        {
            $category = '';
            $category = $request->request->get('category');

            if($category != '')
            {
                    $product_list = $this->getDoctrine()
                    ->getEntityManager()
                    ->getRepository('PATProductBundle:Product')
                    ->selectProductByCategory($category);
            }
            else {
                    $product_list = $em->getRepository('PATProductBundle:Product')->findAll();
            }

            /* POUR DU JSON !!!!!!!!!
            $response = new Response();
            $product = json_encode(array('product_list' =>$product_list));
            $response->headers->set('Content-Type', 'application/json');
            $response->setContent($product);*/

            return $this->container->get('templating')->renderResponse('PATProductBundle:Default:liste.html.twig', 
                    array('product_list' => $product_list
            ));

        }
        else {
            return new Response('ERROR : request is not XmlHttpRequest');
        }
    }
    
    public function ajouterAction(){
        
        //$er = $this->getDoctrine()->getEntityManager()->getRepository('PATProductBundle:Category');
        
        $product = new Product();
        
        $form = $this->createFormBuilder($product)
            ->add('name', 'text', array('label' => 'nom du produit'))
            ->add('category', 'entity', array(
                'label' => 'Catégorie',
                'class' => 'PATProductBundle:Category',
        	'property' => 'name',
                /*'query_builder' => function(CategoryRepository $er) {
                        return $er->selectChildCategory();
                }*/
                ))
            ->add('priceHT', 'number', array('label' => 'Prix')) 
            ->add('quantity', 'integer', array('label' => 'Quantité'))
            ->add('stock', 'entity', array(
                'label' => 'Etat du stock',
                'class' => 'PATProductBundle:Stock',
        	'property' => 'status'))
            ->add('releaseDate', 'date', array('label' => 'Date'))
            ->add('descriptionShort', 'textarea', array('label' => 'Descripton courte'))
            ->add('descriptionLong', 'textarea', array('label' => 'Descripton longue'))
            ->add('picture', new PictureType(), array(
                'label' => "Choix de l'image",
                'required' => false))
            //->add('offers', 'integer', array('required' => false))
            ->getForm();
        
        $request = $this->get('request');

        if( $request->getMethod() == 'POST' )
        {
            $form->bind($request);
            if( $form->isValid() )
            {
                $em = $this->getDoctrine()->getEntityManager();
                $em->persist($product);
                $em->flush();
                return $this->redirect($this->generateUrl('pat_product_display', array('id' => $product->getId())));
            }
        }

        return $this->render('PATProductBundle:Default:add_product.html.twig', array(
          'form' => $form->createView(),
        ));
    }
}

